import tkinter as tk
from tkinter import scrolledtext
import threading
import queue
import time
import os

class LogWindow:
    def __init__(self, log_queue, pause_flag):
        self.log_queue = log_queue
        self.pause_flag = pause_flag
        self.root = tk.Tk()
        self.root.title("实时日志显示")
        self.root.geometry("600x400")

        # 创建滚动文本框
        self.text_area = scrolledtext.ScrolledText(self.root, wrap=tk.WORD, width=70, height=20)
        self.text_area.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)

        # 读取并显示已存在的日志文件
        self.load_existing_logs()

        # 创建暂停按钮
        self.pause_button = tk.Button(self.root, text="暂停", command=self.toggle_pause)
        self.pause_button.pack(pady=10)

        # 启动日志更新线程
        self.update_thread = threading.Thread(target=self.update_log)
        self.update_thread.start()

        self.root.mainloop()

    def load_existing_logs(self):
        file_path = "output/sensor_output.csv"
        if os.path.exists(file_path):
            with open(file_path, "r") as file:
                for line in file:
                    self.text_area.insert(tk.END, line.strip() + "\n")
            self.text_area.see(tk.END)

    def update_log(self):
        while True:
            try:
                log_message = self.log_queue.get(timeout=1)
                self.text_area.insert(tk.END, log_message + "\n")
                self.text_area.see(tk.END)
            except queue.Empty:
                pass

    def toggle_pause(self):
        self.pause_flag[0] = not self.pause_flag[0]
        if self.pause_flag[0]:
            self.pause_button.config(text="恢复")
        else:
            self.pause_button.config(text="暂停")

if __name__ == "__main__":
    log_queue = queue.Queue()
    pause_flag = [False]
    window = LogWindow(log_queue, pause_flag)